<template>
  <div id="app">
    <el-button
      style="margin-left:50px"
      type="primary"
      @click="handleraddPerssion"
      >添加权限</el-button
    >
    <el-table
      :data="perssionList"
      style="width: 95%;margin: 20px auto;"
      row-key="id"
      border
      :tree-props="{ children: 'child', hasChildren: 'hasChildren' }"
      :select-on-indeterminate="false"
      @select="rowSelect"
      @select-all="selectAll"
      @selection-change="selectionChange"
      :header-cell-style="{
        width: '100%',
        background: '#FAFAFA',
        color: '#606266',
        height: '60px'
      }"
      ref="Table"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column
        prop="name"
        label="导航名称"
        width="200"
      ></el-table-column>
      <el-table-column prop="parentId" label="上级ID" width="80">
        <template slot-scope="scoped">
          <div>
            <span v-if="scoped.row.parentId == null" style="color:red"
              >暂无数据</span
            >
            <span v-else>{{ scoped.row.parentId }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="id" label="ID" width="100">
        <template slot-scope="scoped">
          <div>
            <span v-if="scoped.row.id == null" style="color:red">暂无数据</span>
            <span v-else>{{ scoped.row.id }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="sortId" label="排序 " sortable width="100">
        <template slot-scope="scoped">
          <div>
            <span v-if="scoped.row.sortId == null" style="color:red"
              >暂无数据</span
            >
            <span v-else>{{ scoped.row.sortId }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="isLock" label="是否启用 " sortable width="150">
        <template slot-scope="scoped">
          <div>
            <el-switch
              v-model="scoped.row.isLock"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="changeStatus"
              :disabled="lockArr == ''"
            ></el-switch>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="url" label="导航标识" width="200">
        <template slot-scope="scoped">
          <div>
            <span v-if="scoped.row.url == null" style="color:red"
              >暂无数据</span
            >
            <span v-else>{{ scoped.row.url }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="PermissionType" label="操作端" width="250">
        <template slot-scope="scoped">
          <div>
            <span v-if="scoped.row.PermissionType == null" style="color:red"
              >暂无数据</span
            >
            <el-tag v-if="scoped.row.PermissionType == 1">总后台端</el-tag>
            <el-tag type="success" v-if="scoped.row.PermissionType == 2"
              >商户端</el-tag
            >
            <el-tag type="info" v-if="scoped.row.PermissionType == 3"
              >加盟端</el-tag
            >
            <el-tag type="warning" v-if="scoped.row.PermissionType == 4"
              >客户移动端</el-tag
            >
            <el-tag type="danger" v-if="scoped.row.PermissionType == 5"
              >加盟移动端</el-tag
            >
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="address" label="操作" width="350" fixed="right">
        <template slot-scope="scoped">
          <div>
            <el-button
              type="success"
              size="small"
              @click="handlerAddPerssion(scoped.row.id, scoped.row.parentId)"
              >添加子级</el-button
            >
            <el-button
              type="primary"
              size="small"
              @click="handlerEditPerssion(scoped.row)"
              >修改权限</el-button
            >
            <el-button
              type="danger"
              size="small"
              @click="handlerDelPerssion(scoped.row.id)"
              >删除权限</el-button
            >
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[10, 20, 30, 40, 50]"
        :page-size="perssionQuery.pageSize"
        :current-page="perssionQuery.pageNumber"
        layout="total, sizes, prev, pager, next, jumper"
        :total="count"
        class="management_page"
      ></el-pagination>
      <!-- 添加 权限-->
      <el-dialog
        :title="powerName"
        :visible.sync="perssiondialogVisible"
        width="30%"
        :before-close="handleClose"
      >
        <el-form
          :model="PerssionForm"
          :rules="addPerssionRule"
          ref="addPerssionRef"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="名称" prop="name">
            <el-input
              v-model="PerssionForm.name"
              placeholder="请输入名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="操作端" prop="PermissionType">
            <el-select
              v-model="PerssionForm.PermissionType"
              placeholder="请选择操作端"
              @change="handlerPerssion"
            >
              <el-option
                v-for="item in PermissionList"
                :label="item.name"
                :value="item.id"
                :key="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="排序" prop="sortId">
            <el-select v-model="PerssionForm.sortId" placeholder="请选择序号">
              <el-option
                v-for="(item, index) in powerList"
                :label="item"
                :value="index + 1"
                :key="index"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否启用" prop="isLock">
            <el-select
              v-model="PerssionForm.isLock"
              placeholder="请选择启用/不启用"
            >
              <el-option
                v-for="item in isLockList"
                :label="item.name"
                :value="item.isLock"
                :key="item.isLock"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="路由地址" prop="url">
            <el-input
              v-model="PerssionForm.url"
              placeholder="请输入路由地址(   /xxx    )"
            ></el-input>
          </el-form-item>
          <el-form-item label="按钮标识" prop="identification">
            <el-select
              v-model="PerssionForm.identification"
              placeholder="请选择按钮标识"
            >
              <el-option
                v-for="item in buttonList"
                :label="item.name"
                :value="item.name"
                :key="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="perssiondialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handlerSurePerssion"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  powerSel,
  powerLength,
  powerAdd,
  powerUpdate,
  powerDel,
  powerStart
} from "../../utils/api";
export default {
  data() {
    return {
      // 权限列表
      perssionList: [],
      //  权限分页
      perssionQuery: {
        roleId: "",
        pageNumber: 1,
        pageSize: 10
        // PermissionType: 1
      },
      isIndeterminate: true,
      // 总条数
      count: 0,
      // 添加权限的弹框
      perssiondialogVisible: false,
      PerssionForm: {
        name: "",
        sortId: "",
        identification: "",
        parentId: "",
        isLock: "",
        url: "",
        identification: "",
        PermissionType: "",
        userId: "",
        id: ""
      },
      addPerssionRule: {
        name: [{ required: true, message: "请输入页面名称", trigger: "blur" }],
        sortId: [
          { required: true, message: "请输入页面排序", trigger: "blur" }
        ],
        isLock: [
          { required: true, message: "请选择是否启用", trigger: "blur" }
        ],
        url: [{ required: true, message: "请输入路由地址", trigger: "blur" }],
        identification: [
          { required: true, message: "请输入按钮标识", trigger: "blur" }
        ],
        PermissionType: [
          { required: true, message: "请选择操作端", trigger: "blur" }
        ]
      },
      // 添加权限被选中的单选框
      addPerssionName: "菜单",
      // 拿到被选中父类id
      parentId: "",
      // 是否启用数据
      isLockList: [
        {
          isLock: 1,
          name: "未启用"
        },
        {
          isLock: 0,
          name: "启用"
        }
      ],
      // 操作端的数据
      PermissionList: [
        {
          id: 1,
          name: "总后台端"
        },
        {
          id: 2,
          name: "商户端"
        },
        {
          id: 3,
          name: "服务商端"
        }
      ],
      // 权限排序的数据
      powerList: [],
      // 弹框的名字
      powerName: "添加权限",
      // 按钮标识列表
      buttonList: [
        {
          id: 1,
          name: "页面"
        },
        {
          id: 2,
          name: "按钮"
        },
        {
          id: 3,
          name: "菜单"
        }
      ],
      selectArr: [],
      lockArr: [],
      lockstr: "",
      perssionTypeID: ""
    };
  },
  methods: {
    // 获取权限列表
    getperssionList() {
      this.postRequest(powerSel, this.perssionQuery).then(res => {
        if (res.code == 200) {
          res.data.data.map(v => {
            if (v.isLock == 0) {
              v.isLock = true;
            } else if (v.isLock == 1) {
              v.isLock = false;
            }
            v.child.forEach(i => {
              if (i.isLock == 0) {
                i.isLock = true;
              } else if (i.isLock == 1) {
                i.isLock = false;
              }
            });
          });

          this.perssionList = res.data.data;
          this.count = res.data.count;
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    //修改启用和禁用的状态
    changeStatus() {
      // 拿到权限id 抓换为字符串
      this.selectArr = this.selectArr.join(",");
      const lockstr = [];
      this.lockArr.map(v => {
        if (v === true) {
          v = 1;
        } else if (v === false) {
          v = 0;
        }

        lockstr.push(v);
      });
      this.lockstr = lockstr;
      // // 拿到是否开启id
      this.lockstr = this.lockstr.join(",");
      // 参数
      const params = {
        id: this.selectArr,
        isLock: this.lockstr,
        userId: this.PerssionForm.userId
      };
      this.postRequest(powerStart, params).then(res => {
        if (res.code == 200) {
          this.$message.success("修改状态成功");
          this.getperssionList();
        } else {
          this.$message.error("请选择id");
        }
      });
    },
    // 点击表格中复选框拿到父类id
    handleSelectionChange(val) {
      if (val.length > 1) {
        this.$refs.Table.clearSelection();
        this.$refs.Table.toggleRowSelection(val.pop());
      } else {
        if (val.length == 0) {
          this.parentId = [];
        } else {
          this.parentId = val[0].parentId;
        }
      }
    },
    // 切换到某一行的状态
    choosperssionChange(val) {
      this.$refs.Table.toggleRowSelection(val);
    },
    // 添加权限的弹框
    handleraddPerssion() {
      this.powerList = [];
      this.parentId = 0;
      // this.getpowerLength();

      this.perssiondialogVisible = !this.perssiondialogVisible;
    },
    // 添加子级弹框
    handlerAddPerssion(id, parentId) {
      this.powerList = [];
      this.powerName = "添加权限";
      this.parentId = id;
      this.perssiondialogVisible = !this.perssiondialogVisible;
      // this.getpowerLength();
      // if (this.parentId === "" || this.parentId.length == 0) {
      //   this.$message.error("没有父级id,请选择一个父级id");
      // } else {
      //   this.perssiondialogVisible = !this.perssiondialogVisible;
      //   this.getpowerLength();
      // }
    },
    // 编辑权限的弹框
    handlerEditPerssion(data) {
      this.perssiondialogVisible = !this.perssiondialogVisible;
      // console.log(data)
      if (data.isLock == true) {
        this.PerssionForm.isLock = 0;
        console.log(this.PerssionForm.isLock);
      } else if (data.isLock == false) {
        this.PerssionForm.isLock = 1;
      }
      this.$nextTick(() => {
        this.powerName = "编辑权限";

        this.parentId = data.id;
        // this.getpowerLength();
        // this.powerName = "编辑权限";
        // if (this.lockArr == "") {
        //   return this.$message.error("请选择修改权限的数据");
        // } else {

        // }
        this.PerssionForm.name = data.name;
        this.PerssionForm.sortId = data.sortId;
        // this.PerssionForm.isLock = data.isLock;
        this.PerssionForm.url = data.url;
        this.PerssionForm.identification = data.identification;
        this.PerssionForm.PermissionType = data.PermissionType;
        this.PerssionForm.id = data.id;
        this.PerssionForm.parentId = data.parentId;
        this.PerssionForm.userId = this.PerssionForm.userId;
      });
    },
    // 分页
    handleSizeChange(val) {
      this.perssionQuery.pageSize = val;
      this.getperssionList();
    },
    handleCurrentChange(val) {
      this.perssionQuery.pageNumber = val;
      this.getperssionList();
    },
    // 点击确定判断是添加权限还是修改权限
    handlerSurePerssion() {
      this.$refs.addPerssionRef.validate(valid => {
        if (!valid) return this.$message.error("请填写完整");
        if (this.powerName == "添加权限") {
          this.handlerAddPower();
        } else if (this.powerName == "编辑权限") {
          this.handlerEditPower();
        }
      });
    },
    // 封装一个添加权限的方法
    handlerAddPower() {
      const params = {
        name: this.PerssionForm.name,
        sortId: this.PerssionForm.sortId,
        identification: this.PerssionForm.identification,
        parentId: this.parentId,
        isLock: this.PerssionForm.isLock,
        url: this.PerssionForm.url,
        identification: this.PerssionForm.identification,
        PermissionType: this.PerssionForm.PermissionType,
        userId: this.PerssionForm.userId,
        roleId: this.perssionQuery.roleId
      };
      this.postRequest(powerAdd, params).then(res => {
        if (res.code == 200) {
          this.$message.success("添加权限成功");
          this.perssiondialogVisible = false;
          this.getperssionList();
          this.$refs.addPerssionRef.resetFields();
        }
      });
    },
    //封装一个编辑权限的方法
    handlerEditPower() {
      this.postRequest(powerUpdate, this.PerssionForm).then(res => {
        if (res.code == 200) {
          this.$message.success("修改权限成功");
          this.perssiondialogVisible = false;
          this.getperssionList();
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    // 点击操作端下拉获取id
    handlerPerssion(val) {
      this.perssionTypeID = val;

      this.getpowerLength();
    },
    // 点击排序下拉触发的函数
    // handlerPerssionSort() {
    //   if (this.perssionTypeID == "") {
    //    return this.$message.error("请选择操作端");
    //   }
    // },
    //获取权限下拉 排序--
    getpowerLength() {
      this.powerList = [];
      const params = {
        id: this.parentId,
        PermissionType: this.perssionTypeID
      };
      this.postRequest(powerLength, params).then(res => {
        if (res.code == 200) {
          const result = res.data;
          for (var i = 1; i <= result + 1; i++) {
            this.powerList.push(i);
          }
        }
      });
    },
    handleClose() {
      this.perssiondialogVisible = false;
      this.$refs.addPerssionRef.resetFields();
      this.PerssionForm.isLock = "";
    },
    // 删除权限
    handlerDelPerssion(id) {
      const params = {
        id: id,
        userId: this.PerssionForm.userId
      };
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.postRequest(powerDel, params).then(res => {
            if (res.code == 200) {
              this.$message({
                type: "success",
                message: "删除成功!"
              });
              this.getperssionList();
            } else {
              this.$message.error(res.msg);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    selectionChange(selection) {
      // 拿到权限id 和父级的权限id
      const resultarr = [];
      selection.map(v => {
        resultarr.push(v.id);
      });
      const lockarr = [];
      selection.map(v => {
        lockarr.push(v.isLock);
      });

      this.lockArr = lockarr;
      var newArr = new Set(resultarr); //_ddd数组形式不能直接使用
      // 通过array.from方式来使用
      var fin = Array.from(newArr);
      this.selectArr = fin;
      var index = this.selectArr.indexOf(0);
      //大于0 代表存在，
      if (index > -1) {
        //存在就删除
        this.selectArr.splice(index, 1);
      }
    },
    filterSelect(selection) {
      let arr = []; // 循环children取值
      function filterData(val) {
        arr.push(val);
        if (val.child) {
          val.child.map(item => {
            filterData(item);
          });
        }
      } // 源数据中取出选中的数据
      this.perssionList.map(item => {
        selection.map(val => {
          if (val.id === item.id) {
            filterData(val);
          }
        });
      });
      return arr;
    },
    selectAll(selection) {
      let arr = this.filterSelect(selection);
      // 正反选， 过滤后有值勾选，空值清除所有，
      if (arr.length) {
        this.toggleSelection(arr);
      } else {
        // 清除所有
        this.$refs.Table.clearSelection(selection);
      }
    },
    rowSelect(selection, row) {
      let selectArr = [];
      if (selectArr.indexOf(row) === -1) {
        selectArr = this.filterSelect(selection);
        // 正反选， 过滤后有值勾选，空值清除所有，
        if (selectArr.length) {
          this.toggleSelection(selectArr);
        } else {
          // 清除所有
          this.$refs.Table.clearSelection(selection);
        }
      }
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          // toggleRowSelection有两个参数，第一个是每个选中数据，第二个是点击勾选的这行是否选中，树形结构需要，不然子集选中，本身不给选中
          this.$refs.Table.toggleRowSelection(row, true);
        });
      } else {
        this.$refs.Table.clearSelection();
      }
    }
  },
  created() {
    // 拿到角色id
    const userInfo = JSON.parse(window.sessionStorage.getItem("userInfo"));
    this.perssionQuery.roleId = userInfo.roleId;
    // 拿到用户id
    this.PerssionForm.userId = window.sessionStorage.getItem("userId");
    this.getperssionList();
  }
};
</script>
